package com.topsec.manager.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.topsec.manager.entity.NatReq;


/**
 * nat配置工具类 .
 * <p>
 * -----------------------------------------------------------------------------
 * <p>
 * 工程名 ： topsec-web
 *
 * @author 赵艳生
 * @version 3.0
 * @lastMonify 2017年8月4日
 * @since JDK1.7
 */
public class NatUtil {
    //TODO
    // 需要配置文件中读取
    private static String host = "10.96.164.253";
    private static int port = 9990;

    /**
     * 查询nat配置
     *
     * @param req 参数
     * @return string
     */
    public static String findNatConf(String req) {
        return option(host, port, req);
    }

    /**
     * 更新nat配置
     *
     * @param NatReq udp对象
     * @return
     */
    public static String upNatConf(NatReq udp) {

        return null;
    }

    /**
     * 向服务器发送消息
     *
     * @param str cha's
     * @return
     */
    private static String option(String host, int port, String msg) {
        String reply = "";
        try {
            DatagramSocket client = new DatagramSocket();
            // 往服务端发送消息
            byte[] sendBuf;
            sendBuf = msg.getBytes();
            InetAddress addr = InetAddress.getByName(host);
            DatagramPacket sendPacket = new DatagramPacket(sendBuf,
                    sendBuf.length, addr, port);
            client.send(sendPacket);
            // 接收服务器端响应的数据
            byte[] data2 = new byte[1024];
            DatagramPacket packet2 = new DatagramPacket(data2, data2.length);
            client.receive(packet2);
            reply = new String(data2, 0, packet2.getLength());
            System.out.println("收到的服务器信息：" + reply);
            // 关闭DatagramSocket
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reply;
    }

    // 方法测试类
    public static void main(String[] args) {
        try {
            // 新建一个DatagramSocket
            DatagramSocket server = new DatagramSocket(5055);
            // 接收客户端发送来的消息
            byte[] recvBuf = new byte[100];
            DatagramPacket recvPacket = new DatagramPacket(recvBuf,
                    recvBuf.length);
            server.receive(recvPacket);
            String recvStr = new String(recvPacket.getData(), 0,
                    recvPacket.getLength());
            System.out.println("客户端传来消息:" + recvStr);
            // 向客户端响应数据
            InetAddress address = recvPacket.getAddress();
            int port = recvPacket.getPort();
            byte[] data2 = "欢迎您！".getBytes();
            DatagramPacket packet2 = new DatagramPacket(data2, data2.length,
                    address, port);
            server.send(packet2);
            // 关闭DatagramSocket
            server.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //option("127.0.0.1", 5055, new NatReq());
    }
}
